package com.pure.common.syn;

/**
 * @description: 数字反转 力扣
 * @date: 2022-11-09 11:20
 * @since 1.2.0
 **/
public class IntegerReversal {

    public static void main(String[] args) {

        int[] array = {123, -321, 726380, Integer.MAX_VALUE, Integer.MIN_VALUE};
        for (int arr : array) {
            int result = reverseI(arr);
            System.out.println("原整数值：" + arr + "||反转输出==>" + result);
        }
    }

    /**
     * Given a 32-bit signed integer, reverse digits of an integer.
     * <p>
     * Example 1:
     * <p>
     * Input: 123
     * Output: 321
     * Example 2:
     * <p>
     * Input: -123
     * Output: -321
     * Example 3:
     * <p>
     * Input: 120
     * Output: 21
     * Note:
     * Assume we are dealing with an environment which could only store integers within the 32-bit
     * signed integer range: [−2^31,  2^31 − 1]. For the purpose of this problem,
     * assume that your function returns 0 when the reversed integer overflows.
     */
    public static int reverseI(int x) {

        // 难点2：取值范围
        if (Integer.MAX_VALUE <= x || x <= Integer.MIN_VALUE) {
            return 0;
        }

        // 难点1：正负符号
        int sign = x > 0 ? 1 : -1; //记录符号位
        int data = x > 0 ? x : x * sign; //无论正负都当正数处理


        // 1.整数转字符串，再转字符数组
        char[] oldChar = Integer.valueOf(data).toString().toCharArray();

        // 2.反向遍历字符数组，并将元素存储到新数组中
        char[] newChar = new char[oldChar.length];
        for (int i = 0; i < oldChar.length; i++) {//遍历原始数组
            //将原始字符数据 返回遍历给新的newChar数组
            newChar[i] = oldChar[oldChar.length - 1 - i];
        }

        // 3.将newChar新数组转成字符串，再转成整数输出
        long newLong = Long.valueOf(String.valueOf(newChar));
        //数值越界：溢出则返回 0
        int reverse = newLong > Integer.MAX_VALUE ? 0 : (int) newLong;
        return sign * reverse;
    }

}
